package com.qf.web.filter;

import com.qf.domain.User;
import com.qf.sevice.Impl.UserServiceImpl;
import com.qf.sevice.UserService;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        Object user = request.getSession().getAttribute("user");
        if (user != null){
            filterChain.doFilter(request,response);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0){
            response.sendRedirect("/login.jsp");
            filterChain.doFilter(request,response);
            return;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if ("usernameAndPassword".equals(name)){
                String value = cookie.getValue();
                String decode = Base64Utils.decode(value);
                String[] arr = decode.split("#");
                if (arr != null && arr.length == 2){
                    UserService userService = new UserServiceImpl();
                    User user1 = userService.login(arr[0], arr[1]);
                    if (user1 != null) {
                        request.getSession().setAttribute("user",user1);
                        break;
                    }
                }
            }
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }

    public static void main(String[] args) {
        System.out.println("11111111");
        System.out.println("22222222");
        System.out.println("33333333");
    }
}
